package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Visitors;
import com.tanhua.service.VisitorsApi;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author げっしょく
 * @date 2021/11/1
 */
@DubboService
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //保存用户的访问数据
    @Override
    public void saveVisitor(Visitors visitors) {
        //查询条件
        Query query = Query.query(Criteria.where("userId").is(visitors.getUserId())
                .and("visitorUserId").is(visitors.getVisitorUserId())
                .and("visitDate")
                .is(new SimpleDateFormat("yyyyMMdd").format(new Date(System.currentTimeMillis()))));
        Visitors one = mongoTemplate.findOne(query, Visitors.class);
        //判断查询出来的对象是否为空
        if (one == null) {
            //没有对象就保存
            visitors.setDate(System.currentTimeMillis());
            visitors.setVisitDate(new SimpleDateFormat("yyyyMMdd").format(new Date(System.currentTimeMillis())));
            visitors.setFrom("首页");
            mongoTemplate.save(visitors);
        } else {
            //查找出来了就修改访问时间
            Update update = new Update().set("date", System.currentTimeMillis());
            mongoTemplate.updateFirst(query, update, Visitors.class);
        }

    }

    //查找最近的五条访问自己的用户
    @Override
    public List<Visitors> getWhoLookMe(Long id, Long date) {
        //通过id和时间获取最近的五条用户数据,并且要大于自己上一次访问的时间
        Criteria criteria = Criteria.where("userId").is(id);
        if (date != null) {
            criteria.and("date").gt(date);
        }
        Query q = Query.query(criteria).limit(5).with(Sort.by(Sort.Order.desc("date")));
        List<Visitors> visitors = mongoTemplate.find(q, Visitors.class);
        return visitors;
    }

    //分页查找访问了自己用户
    @Override
    public List<Visitors> getPageLookMe(Integer page, Integer pagesize, Long userId) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("date")));
        List<Visitors> visitors = mongoTemplate.find(query, Visitors.class);

        return visitors;
    }
}
